<template>
  <div class="app-container"
       v-loading.fullscreen.lock="allLoading"
       element-loading-text="拼命处理中,请耐心等待"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <el-dialog :close-on-click-modal="changeBitFlagIsNone" :title="mainDialogInfo.title" :visible.sync="showDialog"
               width="90%" append-to-body @close="closeDialog">
      <el-form ref="form" :disabled="changeBitFlagIsNone" :model="form" :rules="rules" label-width="10px">
        <el-row class="mb8">
          <el-col :span="5">
            <el-form-item  required>
              <el-upload
                style="display:grid;"
                ref="field101"
                :file-list="fileList"
                :on-change="handleChangeUpload"
                action="fakeAction"
                drag
                multiple
                :auto-upload="false"
                accept=".md,.txt"
                list-type="text"
                :show-file-list="false"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div slot="tip" style="color:#F56C6C"  class="el-upload__tip">限制文件类型:txt,md等文本文件<br/>验证失败的文件将不会被上传</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="19">
            <el-form-item required>
              <el-table :data="form.virtualDocumentList" default-expand-all style="width: 100%;height: 500px;">
                <el-table-column type="expand" width="40">
                  <template slot-scope="scope">
                    <el-progress  :text-inside="true" :stroke-width="24" :percentage="scope.row.progressPercent"/>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="文件" width="100" :show-overflow-tooltip="false">
                  <template slot-scope="scope">
                    <div style="white-space: pre-wrap; word-break: break-word;">
                      {{ (scope.row.name) }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" width="180" :show-overflow-tooltip="false">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.description"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="fileUploadedSize" label="文件大小" width="180" :show-overflow-tooltip="false">
                  <template slot-scope="scope">
                    <div style="white-space: pre-wrap; word-break: break-word;">
                      {{ formatterText(scope.row) }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="验证" prop="checkMessage" width="80">
                  <template slot-scope="scope">
                    <div style="white-space: pre-wrap; word-break: break-word;">
                      {{ (scope.row.checkMessage) }}
                    </div>
                  </template>
                </el-table-column>
                <!--            <el-table-column prop="progressPercent" label="进度">-->
                <!--              <template slot-scope="scope">-->
                <!--                <el-progress  type="circle" :percentage="scope.row.progressPercent"/>-->
                <!--              </template>-->
                <!--            </el-table-column>-->
                <el-table-column prop="vUploadStatus" label="状态" width="80">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.vUploadStatus==0" type="success">上传成功</el-tag>
                    <el-tag v-else-if="scope.row.vUploadStatus==2" type="danger">上传失败</el-tag>
                    <el-tag v-else type="info">待上传</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="vUploadStatus"  fixed="right" label="操作">
                  <template slot-scope="scope">
                    <!--                <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>-->
                    <el-button v-if="scope.row.vUploadStatus!=0" type="text" size="small" @click="handleReUpload(scope.row)">重新上传</el-button>
                    <el-button v-if="scope.row.vUploadStatus!=0" type="text" size="small" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    <!--                <i class="el-icon-close" @click="handleRemove1(index)"></i>-->
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!--        <template v-if="!changeBitFlagIsNone">-->
        <!--          <el-button type="primary" @click="submitMainDialog">确 定</el-button>-->
        <!--        </template>-->
        <el-button type="primary" @click="uploadFiles">上传到服务器</el-button>
        <el-button @click="handleClose">关 闭</el-button>
        <!--        <el-button @click="uploadFiles">上传到服务器</el-button>-->
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { sksDialogFormMixin } from 'sks-plugin-el-erp/lib/dialog-form'
import request from '@/utils/request'
import { getFileNameWithoutExtension } from '@/utils/str'
import { formatFileSize } from 'sks-plugin-el-erp/lib/core'
import { delKnowledge } from '@/api/knowledge'

export default {
  name: "KnowledgeDocAddDialog",
  components: {  },
  mixins: [
    sksDialogFormMixin,
  ],
  data() {
    return {
      defaultForm: {
        id: undefined,
        //描述
        description: undefined,
        //备注
        remark: undefined,
        kb_id: undefined,
      },
      defaultFormNotNull: {
        //上传点击后存储的file
        vFileList:[],
        //上传文件的列表,因为直接将待上传的file push进来无法刷新行信息
        virtualDocumentList: [],
      },
      extra:{
        kb_id: undefined,
      },

      fileList:[],
      uploadUrl: '',

      rules: {
        description: [
          {required: true, message: '不能为空', trigger: "blur"},
        ],
      },
      test: 1,
      tableData: [
        { id: 1, name: 'John Doe', email: 'john@example.com' },
        { id: 2, name: 'Jane Smith', email: 'jane@example.com' }
        // 其他用户数据
      ]
    };
  },
  methods:{
    showByUniqueId({uniqueId,extra,dialogInfo,virtualChangeBitFlag=this.sksUtils.CHANGE_BIT_FLAG.none}){
      let data={
        id: 1,
        description: '蒋校长',
        remark: '这是测试数据'
      }
      this.show({
        extra: extra,
        form: this.sksUtils.mergeFromObject({},data,{
          virtualChangeBitFlag: virtualChangeBitFlag,
        }),
        dialogInfo: dialogInfo
      })
    },
    validateSuccess() {
      let data = this.sksUtils.mergeFromObject({}, this.form);

      if (!this.sksUtils.isNullOrUndefined(this.mainDialogInfo.submitCallback)) {
        this.mainDialogInfo.submitCallback({submitData: data, ref: this})
        //this.showDialog=false
        return
      }
      switch(data.virtualChangeBitFlag) {
        case this.sksUtils.CHANGE_BIT_FLAG.add:
          this.closeDialog()
          this.sksUtils.msgSuccess("新增成功");
          //此处换成新增接口 start
          //新增接口返回新增后的数据
          let saRes={
            data: this.sksUtils.mergeFromObject({},data,{
              id: 1000,
            })
          }
          //此处换成新增接口 end
          if (!this.sksUtils.isNullOrUndefined(this.mainDialogInfo.submitCallbackSuccess)){
            this.mainDialogInfo.submitCallbackSuccess({resData: saRes.data})
          }
          break;
        case this.sksUtils.CHANGE_BIT_FLAG.modify:
          this.closeDialog()
          this.sksUtils.msgSuccess("修改成功");
          if (!this.sksUtils.isNullOrUndefined(this.mainDialogInfo.submitCallbackSuccess)){
            this.mainDialogInfo.submitCallbackSuccess({resData: data})
          }
          break;
        default:
          this.sksUtils.msgError("未知的变更标识");
          break;
      }
    },
    nowTime() {
      const now = new Date();

      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始要+1
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      const milliseconds = String(now.getMilliseconds()).padStart(3, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
    },

    handleUpload(options) {
      //只能一个一个上传,显示进度只能显示一个文件的进度
      console.log('handleUpload',options)
      console.log('this.form.virtualDocumentList',this.form.virtualDocumentList)
      const file=options.file
      const fileInfo=options.fileInfo
      const formData = new FormData();
      formData.append('files', file);
      formData.append('kb_id',this.form.kb_id)
      formData.append('file_description',fileInfo.description)
      request({
        isQuery: true,
        url: `/api/knowledge/documents/upload`,
        method: 'post',
        params: {},
        data: formData,
        timeout: 300000,
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (progressEvent) => {
          console.log(progressEvent)
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);

          // onUploadProgress({ percent });
          // 更新文件对象的进度
          console.log(`上传中 ${this.nowTime()}      ${percent}%`)
          let index=this.form.virtualDocumentList.findIndex(f=>f.uid===file.uid)
          if (index !== -1) {
            let tmp_file = this.form.virtualDocumentList[index]
            console.log(`${file.name}  ${progressEvent.loaded}/${tmp_file.fileSize}  ${percent}%`)
            this.$set(tmp_file, 'fileUploadedSize', progressEvent.loaded);
            this.$set(tmp_file, 'progressPercent', percent);
            this.$set(this.form.virtualDocumentList, index, tmp_file);
          }
        }
      }) .then(response => {
        console.log("handleUpload.success")
        // 设置文件上传成功状态
        const index = this.form.virtualDocumentList.findIndex(f => f.uid === file.uid);
        if (index !== -1) {
          let tmp_file = this.form.virtualDocumentList[index]
          this.$set(tmp_file, 'vUploadStatus', 0);
          this.$set(tmp_file, 'fileUploadedSize', file.size);
          this.$set(tmp_file, 'progressPercent', 100);
          console.log(`上传成功 ${file.name}  ${tmp_file.size}/${tmp_file.fileSize} 100%`)
        }
      }).catch(error => {
        console.log("handleUpload.error",error)
        const index = this.form.virtualDocumentList.findIndex(f => f.uid === file.uid);
        if (index !== -1) {
          let tmp_file = this.form.virtualDocumentList[index]
          //上传失败
          this.$set(tmp_file, 'vUploadStatus', 2);
        }
      });
    },
    // 检查文件
    checkUploadFile(file,fileInfo) {
      let checkMessage=[]
      let maxFileSize=10//10MB
      console.log(file)
      //10MB
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        checkMessage=`上传文件大小不能超过 ${maxFileSize}MB!`
      }
      fileInfo.checkMessage=checkMessage.join()
    },
    formatterText(file){
      // 数据小于0.1M的时候按KB显示
      // const size = file.size/1024/1024 > 0.1 ? `(${(file.size/1024/1024).toFixed(1)}M)` : `(${(file.size/1024).toFixed(1)}KB)`
      // file.name.indexOf('M')>-1 || file.name.indexOf('KB')>-1 ? file.name : file.name += size

      return `文件大小:${formatFileSize(file.fileSize)}\n  已上传:${formatFileSize(file.fileUploadedSize)}`
    },
    beforeUpload(fileInfo) {
      //已上传的忽略
      if(fileInfo.vUploadStatus==0)return false
      //验证失败的忽略
      if(!this.sksUtils.strIsEmpty(fileInfo.checkMessage))return false
      return true
    },
    uploadFiles() {
      if(this.form.vFileList.length==0){
        this.sksUtils.msgError("还未选择要上传的文件")
        return
      }
      for (let i = 0; i < this.form.virtualDocumentList.length; i++) {
        const file=this.form.vFileList[i]
        const fileInfo=this.form.virtualDocumentList[i]
        this.checkUploadFile(file,fileInfo)
        if(!this.beforeUpload(fileInfo))continue
        this.handleUpload({ file:file.raw,fileInfo:fileInfo})
      }
      // this.form.virtualDocumentList.forEach(file=>this.checkUploadFile(file))
      // let files=this.form.virtualDocumentList.filter(f=>{
      //   if(f.vUploadStatus==0) return false
      //   if(!this.sksUtils.strIsEmpty(f.checkMessage))return false
      //   return true
      // })
      // for (let i = 0; i < files.length; i++) {
      //   this.handleUpload({ file:files[i].raw})
      // }
    },
    handleReUpload(fileInfo){
      fileInfo.fileUploadedSize=0
      fileInfo.progressPercent=0
      if(!this.beforeUpload(fileInfo))return
      let index=this.form.virtualDocumentList.findIndex(f=>f.uid===fileInfo.uid)
      const file=this.form.vFileList[index]
      this.handleUpload({ file:file.raw,fileInfo:fileInfo})
    },
    handleChangeUpload(file){
      let fileInfo={}
      fileInfo.name=file.name
      fileInfo.uid=file.uid
      console.log(file)
      // 初始化文件描述和进度
      fileInfo.description = getFileNameWithoutExtension(file.name);
      //上传进度百分比
      fileInfo.progressPercent = 0;
      // 已上传文件字节数
      fileInfo.fileUploadedSize=0
      fileInfo.isSuccess=false
      //0:上传成功,1:待上传,2:上传失败
      fileInfo.vUploadStatus=1
      //验证错误消息,如果存在错误消息,上传时将会忽略
      fileInfo.checkMessage=''
      fileInfo.fileSize=file.size
      fileInfo.raw=undefined

      this.checkUploadFile(file,fileInfo)
      this.form.virtualDocumentList.push(fileInfo)
      this.form.vFileList.push(file)
      this.fileList=[]
    },
    handleDelete(index){
      this.form.virtualDocumentList.pop(index)
      this.form.vFileList.pop(index)
    },
    handleClose(){
      //如果有一个未上传成功,则提示关闭
      let allSuccess=true
      for (let i = 0; i < this.form.virtualDocumentList.length; i++) {
        const file = this.form.vFileList[i]
        const fileInfo = this.form.virtualDocumentList[i]
        if (fileInfo.vUploadStatus != 0) {
          allSuccess=false
        }
      }
      if(allSuccess){
        this.cancelMainDialog()
        return
      }
      this.$modal.confirm('存在未上传成功的文件,是否强制退出？').then(() => {
        this.cancelMainDialog()
      })
    },
    closeDialogBefore(){
      console.log('----------closeDialogBefore')
      if(this.mainDialogInfo?.closeCallback){
        this.mainDialogInfo.closeCallback()
      }
    }
  }
}
</script>

<style scoped>
/deep/ .el-upload-dragger {
  width: 100%; /* 设置宽度 */
  height: 250px; /* 设置高度 */
}
/deep/ .el-upload .el-upload-dragger{
  width: 100%; /* 设置宽度 */
  height: 250px; /* 设置高度 */
}
</style>

<!--/deep/ .el-upload-dragger {-->
<!--width: 200px; /* 设置宽度 */-->
<!--height: 200px; /* 设置高度 */-->
<!--}-->
<!--/deep/ .el-upload .el-upload-dragger{-->
<!--width: 200px; /* 设置宽度 */-->
<!--height: 200px; /* 设置高度 */-->
<!--}-->
